class Solution {
public:
    int arithmeticTriplets(vector<int>& nums, int diff) {
        int a = 0, b = 0, c = 0, n = nums.size(), ans = 0;
        for (; c < n; c++) {
            while (nums[c] - nums[b] > diff) {
                b++;
            }
            while (nums[b] - nums[a] > diff) {
                a++;
            }
            if(nums[c] - nums[b] == diff && nums[b] - nums[a] == diff)
                ans++;
        }
        return ans;
    }
};
class Solution {
public:
    long long countFairPairs(vector<int>& nums, int lower, int upper) {
        int  n = nums.size(),a = 0, b = 0, c = n - 1;
        sort(nums.begin(), nums.end());
        long long ans = 0;
        for (; c > a; c--) {
            while (a < c && nums[c] + nums[a] < lower) {
                a++;
            }
            while (b < c && nums[c] + nums[b] <= upper) {
                b++;
            }
            ans += max(min(c,b) - a,0);
            // cout << a  <<' '<<  b  << ' '<< c << endl;
        }
        return ans;
    }
};
class Solution {
public:
    int numSubarrayBoundedMax(vector<int>& nums, int left, int right) {
        int n = nums.size(),l = -1,r = -1,ans = 0;
        for(int i = 0;i < n;i++){
            if(nums[i] > right)  r = i;
            if(nums[i] >= left) l = i;
            ans += l - r;
        }
        return ans;
    }
};
class Solution {
public:
    int maxFrequency(vector<int>& nums, int k, int numOperations) {
        sort(nums.begin(), nums.end());
        int pos = 0, n = nums.size(), l = 0, r = 0, ans = 0, cnt = 0;
        for (; pos < n; pos++) {
            cnt++;
            if (pos < n - 1 && nums[pos] == nums[pos + 1])
                continue;
            while (nums[pos] - nums[l] > k)
                l++;
            while (r < n && nums[r] - nums[pos] <= k)
                r++;
            ans = max(ans, min(r - l, cnt + numOperations));
            cnt = 0;
        }
        if (ans >= numOperations)
            return ans;

        for (l = 0, pos = 0; pos < n; pos++) {
            while (nums[pos] - nums[l] > 2*k)
                l++;
            ans = max(ans,pos - l + 1);
        }
        return min(ans,numOperations);
    }
};